package com.konsung.ksdc.manager.shop;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.ArrayMap;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.ProductInfoBean;
import com.konsung.ksdc.bean.netbean.CartDetailNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.ConfirmPopupWindow;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 购物车页面
 * Created by Administrator on 2016/5/3 0003.
 */
public class ShoppingCartActivity extends BaseActivity {
    private static final int MSG_CART_EMPTY = 10000;
    private static final int MSG_UPDATE_CART = 10001;
    public static final String TYPE_BUY = "type_buy";
    public static final int TYPE_BUY_CART = 10200;
    public static final String CART_IDS = "cart_ids";
    public static final int COUNT_EXCEED = 2;
    private static final String SHOP_CART_EMPTY = "0";

    @Bind(R.id.ll_shopping_cart_root)
    LinearLayout llRootView;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tab_tv_title)
    TextView tabTvTitle;
    @Bind(R.id.lv_buy_list)
    SwipeMenuListView lvBuyList;
    @Bind(R.id.btn_buy)
    Button btnBuy;
    @Bind(R.id.tv_sum)
    TextView tvSum;
    @Bind(R.id.ll_empty)
    LinearLayout llEmpty;
    @Bind(R.id.btn_go)
    Button btnGo;
    @Bind(R.id.iv_abnormal)
    ImageView ivAbnormal;
    @Bind(R.id.tv_abnormal_type)
    TextView tvAbnormalType;
    @Bind(R.id.tv_abnormal_text)
    TextView tvAbnormalText;
    @Bind(R.id.ll_not_empty)
    LinearLayout llNotEmpty;
    @Bind(R.id.cbx_select_all)
    CheckBox cbxSelectAll;
    @Bind(R.id.tv_delete)
    TextView tvDelete;
    @Bind(R.id.ll_check)
    LinearLayout llCheck;

    public static final String KEY_DATA = "datas";
    public static final String KEY_SUM = "sum";
    private double sum;
    private List<CartDetailNetBean> cartDetailNetBeans;
    private SwipeMenuCreator creator;
    private String catIds;
    private BuyListAdapter adapter;
    private WaitingDialog waitDialog;
    private ConfirmPopupWindow popupWindow;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BuyListAdapter.MSG_UPDATE_SUM:
                    Bundle data = msg.getData();
                    int account = data.getInt("account", 0);
                    sum = data.getDouble("sum", 0.00);
                    btnBuy.setText(appendAccountStr(account));
                    tvSum.setText(appendSumStr(sum));
                    requestUpdateCart();
                    break;
                case MSG_CART_EMPTY:
                    waitDialog.dismiss();
                    llEmpty.setVisibility(View.VISIBLE);
                    llNotEmpty.setVisibility(View.GONE);
                    break;
                case MSG_UPDATE_CART:
                    waitDialog.dismiss();
                    llEmpty.setVisibility(View.GONE);
                    llNotEmpty.setVisibility(View.VISIBLE);
                    adapter = new BuyListAdapter(ShoppingCartActivity.this,
                            cartDetailNetBeans, handler);
                    lvBuyList.setAdapter(adapter);
                    btnBuy.setText(appendAccountStr(adapter
                            .getProductAccount()));

                    sum = adapter.getProductSum();
                    String s1 = StringUtils
                            .trans2double(adapter.getProductSum());
                    tvSum.setText(StringUtils.appendPay(s1));
                    break;
                case COUNT_EXCEED:
                    waitDialog.dismiss();
                    llEmpty.setVisibility(View.VISIBLE);
                    llNotEmpty.setVisibility(View.GONE);
                    ivAbnormal.setImageResource(R.drawable.connect_server_fail);
                    tvAbnormalType.setText(R.string.get_data_fail);
                    tvAbnormalText.setVisibility(View.GONE);
                    btnGo.setText(R.string.reload);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected String activityDesc() {
        return getString(R.string.page_shopping_cart);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    /**
     * 初始化购物车数据
     */
    private void initData() {
        if (llEmpty != null) {
            //重新加载数据，不显示图片
            llEmpty.setVisibility(View.GONE);
        }
        if (waitDialog == null) {
            waitDialog = new WaitingDialog(this, "");
            waitDialog.setText(getString(R.string.tip_loader));
            waitDialog.show();
        } else {
            waitDialog.show();
        }
        if (!RequestUtils.checkNetwork(this)) {
            waitDialog.dismiss();
            llEmpty.setVisibility(View.VISIBLE);
            llNotEmpty.setVisibility(View.GONE);
            ivAbnormal.setImageResource(R.drawable.no_wifi);
            tvAbnormalType.setText(R.string.wifi_not_well);
            tvAbnormalText.setVisibility(View.VISIBLE);
            tvAbnormalText.setText(R.string.check_your_network);
            btnGo.setText(R.string.refresh);
            return;
        }
        RequestUtils.showCatDetail(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(ShoppingCartActivity.this,
                                getString(R.string.chat_unconnect));
                        handler.sendEmptyMessage(COUNT_EXCEED);
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (responseBean.getResultCode().equals(Constants
                                .REQUEST_OK)) {
                            cartDetailNetBeans = responseBean.getList(new
                                    TypeToken<List<CartDetailNetBean>>() {
                                    }.getType());
                            if (cartDetailNetBeans != null &&
                                    cartDetailNetBeans.size() > 0) {
                                handler.sendEmptyMessage(MSG_UPDATE_CART);
                            } else {
                                //购物车为空
                                handler.sendEmptyMessage(MSG_CART_EMPTY);
                            }
                        }
                    }
                });
    }

    /**
     * 初始化组件，（商品条目里的creator(删除按钮)）
     */
    private void initView() {
        tvDelete.setVisibility(View.VISIBLE);
        tabTvTitle.setText(R.string.title_shopping_cart);
        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnGo.getText().toString().equals(getString(R.string.x_btn_text))) {
                    finish();
                } else {
                    initData();
                }
            }
        });
        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<CartDetailNetBean> selectedBeanList = adapter.getSelectedList();
                if (selectedBeanList == null || selectedBeanList.size() == 0) {
                    Toast.makeText(ShoppingCartActivity.this, R.string.buy_select_product_first,
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!RequestUtils.checkNetwork(ShoppingCartActivity.this)) {
                    return;
                }
                Intent intent = new Intent(ShoppingCartActivity.this,
                        OrderConfirmActivity.class);
                intent.putParcelableArrayListExtra(KEY_DATA, (ArrayList<? extends Parcelable>)
                        selectedBeanList);
                intent.putExtra(CART_IDS, catIds);
                intent.putExtra(TYPE_BUY, TYPE_BUY_CART);
                intent.putExtra(KEY_SUM, sum);
                startActivity(intent);
            }
        });

        creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getApplicationContext());
                // set text color size
                deleteItem.setTitle(getString(R.string.btn_delete));
                deleteItem.setTitleSize(15);
                // set a icon
                deleteItem.setIcon(R.drawable.ic_delete2);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color
                        .rgb(247, 132, 7)));
                // set item width
                deleteItem.setWidth(DensityUtils.dp2px(ShoppingCartActivity.this, 50));
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        // set creator
        lvBuyList.setMenuCreator(creator);

        // step 2. listener item click event
        lvBuyList.setOnMenuItemClickListener(new SwipeMenuListView
                .OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(final int position, SwipeMenu
                    menu, int index) {
                long currentTime = System.currentTimeMillis();
                long lastClickTime = 0l;
                if (currentTime - lastClickTime < 500) {
                    return;
                }
                lastClickTime = currentTime;
                if (cartDetailNetBeans != null) {
                    CartDetailNetBean item = cartDetailNetBeans.get(position);
                    switch (index) {
                        case 0:
                            // 侧滑删除
                            deleteProductInCart(position, item);
                            break;
                        default:
                            break;
                    }
                }
            }
        });

        // set SwipeListener
        lvBuyList.setOnSwipeListener(new SwipeMenuListView
                .OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });

        lvBuyList.setOnItemClickListener(new SwipeMenuListView.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ProductInfoBean bean = new ProductInfoBean(cartDetailNetBeans.get(position)
                        .getProductId(), "", "", "", "");
                Intent intent = new Intent(ShoppingCartActivity.this, ProductDetailActivity.class);
                String productIconUrl = bean.getProductIconUrl();

                intent.putExtra(ProductDetailActivity.PRODUCT_INFO_DATA, bean);
                intent.putExtra(ProductDetailActivity.PRODUCT_ICON_URL, productIconUrl);
                startActivity(intent);
            }
        });

        cbxSelectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setAllChecked(true);
                } else {
                    setAllChecked(false);
                }
            }
        });

        tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == adapter) {
                    ToastUtils.toastContent(ShoppingCartActivity.this, getString(R.string
                            .tip_shopcart_no));
                    return;
                }
                final Map<Integer, Boolean> map = adapter.getIsCheckedList();
                //得到选中map集合，选中为true
                Set<Integer> set = map.keySet();
                // 遍历键的集合，获取得到每一个键
                for (Integer key : set) {
                    // 根据键去找值
                    boolean value = map.get(key);
                }
                if (null == map || map.size() <= 0) {
                    ToastUtils.toastContent(ShoppingCartActivity.this, getString(R.string
                            .select_product_first));
                    return;
                }
                popupWindow = new ConfirmPopupWindow(ShoppingCartActivity.this,
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                List<CartDetailNetBean> selectList = adapter.getSelectedList();
                                deleteProductsInCart(selectList);
                            }
                        },

                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                popupWindow.dismiss();
                                cbxSelectAll.setChecked(false);
                                setAllChecked(false);
                            }
                        });
                popupWindow.setTips(getString(R.string.delete_product_confirm));
                popupWindow.setTitle(getString(R.string.delete_product));
                popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
            }
        });

        llCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbxSelectAll.isChecked()) {
                    cbxSelectAll.setChecked(false);
                } else {
                    cbxSelectAll.setChecked(true);
                }
            }
        });
    }

    /**
     * 批量删除购物车商品
     * @param selectList 要删除的bean
     */
    private void deleteProductsInCart(final List<CartDetailNetBean> selectList) {
        RequestUtils.deleteCatByIds(appendProductId(selectList), new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                popupWindow.dismiss();
                ToastUtils.toastContent(ShoppingCartActivity.this, getString(R.string
                        .delete_product_fail));
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                popupWindow.dismiss();
                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                    for (CartDetailNetBean bean : selectList) {
                        PreferenceUtils.putString(ShoppingCartActivity.this, bean
                                .getProductName(), SHOP_CART_EMPTY);
                    }
                    cartDetailNetBeans.removeAll(selectList);
                    //被选中的数据也要清空
                    adapter.getSelectedList().clear();
                    if (cartDetailNetBeans.size() <= 0) {
                        initData();
                    } else {
                        adapter.setData(cartDetailNetBeans);
                        //重新让结算和合计加个为0
                        btnBuy.setText(appendAccountStr(0));
                        tvSum.setText(appendSumStr(0.0));
                    }
                    cbxSelectAll.setChecked(false);
                    setAllChecked(false);
                } else {
                    ToastUtils.toastContent(ShoppingCartActivity.this, getString(R.string
                            .delete_product_fail));
                }
            }
        });
    }

    /**
     * 拼接商品id
     * @param beanList 需要购买的商品集合
     * @return 拼接后的id
     */
    private String appendProductId(List<CartDetailNetBean> beanList) {
        //遍历购物车，赋值
        StringBuilder builder = new StringBuilder();
        for (CartDetailNetBean bean : beanList) {
            String catId = bean.getCatId();
            builder.append(catId).append(",");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    /**
     * 设置是否全选
     * @param allChecked 全选按钮状态
     */
    private void setAllChecked(boolean allChecked) {
        //通过adapter来进行全选反选操作
        adapter.setAllCheck(adapter.getCount(), allChecked);
//        adapter.notifyDataSetChanged();
        lvBuyList.setAdapter(adapter);
        //如果不全选，设置计算为0
        if (!allChecked) {
            btnBuy.setText(appendAccountStr(0));
            tvSum.setText(appendSumStr(0.0));
        }
    }

    /**
     * 从购物车中将产品条目的删除
     * @param position item位置
     * @param item 购物车bean
     */
    private void deleteProductInCart(final int position, final CartDetailNetBean item) {
        // 发送网络请求，删除了购物车中的产品
        String catId = item.getCatId();
        RequestUtils.deleteCatById(catId, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                    if (cartDetailNetBeans != null) {
                        // 避免删除条目一直走BuyListAdapter的死循环
                        if (cartDetailNetBeans.size() > 0) {
                            // 删掉购物车的条目，把存储的数据也清掉
                            PreferenceUtils.putString(ShoppingCartActivity.this, item
                                    .getProductName(), SHOP_CART_EMPTY);
                            cartDetailNetBeans.remove(item);
                            //选中数据清0
                            adapter.getSelectedList().clear();
                            if (cartDetailNetBeans.size() > 0) {
                                //设置滑动删除的boolen值为false
                                adapter.setData(cartDetailNetBeans);
                                btnBuy.setText(appendAccountStr(0));
                                tvSum.setText(appendSumStr(0.0));
                            } else {
                                //没有数据，重新获取数据
                                initData();
                            }
                        } else {
                            // ### 如果购物车中已经没有数据了 界面更新 ###
                            handler.sendEmptyMessage(MSG_CART_EMPTY);
                        }
                        cbxSelectAll.setChecked(false);
                        setAllChecked(false);
                    }
                }
            }
        });
    }

    /**
     * 拼接商品数量字符串
     * @param account 商品总数
     * @return 商品数量
     */
    public String appendAccountStr(int account) {
        return getString(R.string.append_sum_left) + account + getString(R
                .string.append_sum_right);
    }

    /**
     * 拼接商品总额字符串
     * @param sum 商品总数
     * @return 总金额
     */
    private String appendSumStr(double sum) {
        return StringUtils.appendPay(sum);
    }

    /**
     * 发送请求，更新购物车中数据
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void requestUpdateCart() {
        Map<String, String> map = new ArrayMap<>();
        if (adapter != null) {
            cartDetailNetBeans = adapter.getData();
            if (cartDetailNetBeans != null && cartDetailNetBeans.size() > 0) {
                for (CartDetailNetBean bean : cartDetailNetBeans) {
                    String catId = bean.getCatId();
                    String number = bean.getShopNumber();
                    map.put(catId, number);
                }
            }
        }

        RequestUtils.updateCat(map, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
            }
        });
    }

    /**
     * 返回点击事件
     */
    @OnClick(R.id.rl_back)
    public void onClick() {
        finish();
    }

    /**
     * 在onResume之前是否隐藏lvBuyList
     */
    @Override
    protected void onStart() {
        super.onStart();
        //如果提交清单，提前把list隐藏，避免陷入lvBuyList显示循环
        if (Constants.isHideBuyList) {
            llNotEmpty.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //每次进来重置提交按钮为false,进入adapter的逻辑
        Constants.isCartSubmit = false;
        cbxSelectAll.setChecked(false);
        RequestUtils.showCatDetail(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtils.toastContent(ShoppingCartActivity.this,
                                getString(R.string.chat_unconnect));
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (responseBean.getResultCode().equals(Constants
                                .REQUEST_OK)) {
                            cartDetailNetBeans = responseBean.getList(new
                                    TypeToken<List<CartDetailNetBean>>() {
                                    }.getType());
                            if (cartDetailNetBeans != null) {
                                if (cartDetailNetBeans.size() > 0) {
                                    handler.sendEmptyMessage(MSG_UPDATE_CART);
                                }
                            } else {
                                llEmpty.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }
}
